package com.wyp.didishige.fragment;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.wyp.didishige.activity.NewDynamicActivity;
import com.wyp.didishige.R;
import com.wyp.didishige.activity.MainActivity;
import com.wyp.didishige.activity.DynamicDetailActivity;
import com.wyp.didishige.adapter.DiscoverAdapter;
import com.wyp.didishige.config.Constants;
import com.wyp.didishige.model.Dynamic;
import com.wyp.didishige.model.User;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.wiget.xlist.XListView;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.listener.FindListener;

/**
 * 附近的人
 * A placeholder fragment containing a simple view.
 */
public class DiscoverFragment extends FragmentBase implements View.OnClickListener, XListView.IXListViewListener {

    private static final String ARG_SECTION_NUMBER = "section_number";

    BmobGeoPoint geoPoint;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();

    List<Dynamic> dynamicList;
    private static final String USER = "user";

    XListView nearby_list;
    User user;
    DiscoverAdapter nearByAdapter;
    /**
     * 新建动态
     */
    FloatingActionButton new_dynamic;

    private SwipeRefreshLayout hullSwipe = null;

    View rootView = null;

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static DiscoverFragment newInstance(int sectionNumber) {
        DiscoverFragment fragment = new DiscoverFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);

        return fragment;
    }

    public DiscoverFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_nearby, container, false);


        user = userManager.getCurrentUser(User.class);

        initView();

        return rootView;
    }

    private void initView() {
        nearby_list = (XListView) rootView.findViewById(R.id.nearby_list);
        hullSwipe = (SwipeRefreshLayout) rootView.findViewById(R.id.hullSwipe);
        new_dynamic = (FloatingActionButton) rootView.findViewById(R.id.new_dynamic);
        new_dynamic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtil.start_activity_for_result(getActivity(), NewDynamicActivity.class, MainActivity.MSG_REFRESH_DYNAMIC_CODE);
            }
        });
        initListView();
        getLocation();
    }

    private void initListView() {

        hullSwipe.setColorSchemeResources(R.color.btn_blue, R.color.vip_male);
        hullSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                getNearByList(true);
            }
        });
        nearby_list.setPullLoadEnable(false);
        nearby_list.setXListViewListener(this);
        nearByAdapter = new DiscoverAdapter(getActivity(), new ArrayList<Dynamic>());
        nearby_list.setAdapter(nearByAdapter);
        nearby_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle;
                bundle = new Bundle();
                Dynamic Dynamic = (Dynamic) nearByAdapter.getItem(position);
                bundle.putString(Constants.DYNAMIC_ID, Dynamic.getObjectId());
                IntentUtil.start_activity_for_result(getActivity(), DynamicDetailActivity.class, MainActivity.MSG_REFRESH_DYNAMIC_CODE, bundle);
            }
        });
    }

    /**
     * 定位
     */
    private void getLocation() {
        // 定位初始化
        mLocClient = new LocationClient(getActivity());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
//        option.setScanSpan(2000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                reverseGeoCode(location);
                geoPoint = new BmobGeoPoint(location.getLongitude(), location.getLatitude());
            } else {
                // 无定位数据默认北京中心
                double cLat = 39.909230;
                double cLon = 116.397428;
                geoPoint = new BmobGeoPoint(cLon, cLat);
            }

            //更新当前位置
            ((MainActivity) getActivity()).refreshPoint(geoPoint);


            if (user != null) {
                user.setCity(location.getCity());
                user.setLocation(geoPoint);
                user.update(getActivity());
            }
            onRefresh();
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    /**
     * 地理反编码获取用户详细地址
     *
     * @param location
     */
    private void reverseGeoCode(BDLocation location) {
        GeoCoder geoCoder = GeoCoder.newInstance();
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(location.getLatitude(), location.getLongitude())));
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                if (null == user) return;
                user.setCity(reverseGeoCodeResult.getAddressDetail().city);
                user.setProvince(reverseGeoCodeResult.getAddressDetail().province);
                user.setDistrict(reverseGeoCodeResult.getAddressDetail().district);
                user.setStreet(reverseGeoCodeResult.getAddressDetail().street);
                user.setStreetNumber(reverseGeoCodeResult.getAddressDetail().streetNumber);
                user.update(getActivity());
            }
        });
    }

    @Override
    public void onClick(View v) {

    }

    int page = 0;
    int limit = 20;

    private void getNearByList(final boolean isRefresh) {
        BmobQuery<Dynamic> query = new BmobQuery<Dynamic>();
        query.addWhereWithinKilometers("location", geoPoint, 5000);
        query.setLimit(limit);
        query.setSkip(limit * page);
        query.include("author,images");
        query.order("-createdAt");
        query.findObjects(getActivity(), new FindListener<Dynamic>() {
            @Override
            public void onSuccess(List<Dynamic> Dynamics) {
                dynamicList = Dynamics;
                nearby_list.stopLoadMore();
                if (Dynamics != null && Dynamics.size() != 0) {
                    LatLng ll;
                    for (Dynamic info : dynamicList) {
                        BmobGeoPoint point = info.getLocation();
                        if (point == null) continue;
                        ll = new LatLng(point.getLatitude(), point.getLongitude());
                        int meter = (int) DistanceUtil.getDistance(ll, new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()));
                        info.setMeter(meter);
                    }

                    nearby_list.setPullLoadEnable(true);
                    if (isRefresh) {
                        nearByAdapter.setList(Dynamics);
                    } else {
                        nearByAdapter.addAll(Dynamics);
                    }

                    page++;
                } else {
                    nearby_list.setFooterText("加载完毕");
                }
            }

            @Override
            public void onFinish() {
                hullSwipe.setRefreshing(false);
                nearby_list.setVisibility(View.VISIBLE);
            }

            @Override
            public void onError(int i, String s) {
                ShowToast(s);
                nearby_list.stopLoadMore();
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        user = userManager.getCurrentUser(User.class);
    }

    @Override
    public void onDestroy() {
        mLocClient.stop();

        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        hullSwipe.setRefreshing(true);
        page=0;
        getNearByList(true);
    }

    @Override
    public void onLoadMore() {
        getNearByList(false);
    }

}

